package generics.practices;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

import net.mindview.util.TwoTuple;

public class ModityProxy implements InvocationHandler{
	
	Map<String, Object> objectMap;
	public ModityProxy(TwoTuple<Object, Class<?>>... tuples){
		objectMap = new HashMap<String, Object>();
		for(TwoTuple<Object, Class<?>> tuple : tuples){
			Object obj = tuple.second;
			for(Method method : tuple.second.getMethods()){
				String methodName = method.getName();
				if(!objectMap.containsKey(methodName))
					objectMap.put(methodName, obj);
			}
		}
	}

	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		String methodName = method.getName();
		Object obj = objectMap.get(methodName);
		return method.invoke(obj, args);
	}
	
	public static Object newInstance(TwoTuple<Object, Class<?>>... tuples){
		return Proxy.newProxyInstance(ModityProxy.class.getClassLoader(), tuples.getClass().getInterfaces(), new ModityProxy(tuples));
	}
	
	
}
